//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 张婷 on 15/10/22.
//  Copyright © 2015年 itheima. All rights reserved.
//

import Foundation

/// 用户账户视图模型
class UserAccountViewModel {
    
    /// 单例对象，防止多次从沙盒中读取数据，影响效率
    static let sharedUserAccountModel = UserAccountViewModel()
    
    /// 用户账户
    var userAccount: UserAccount?
    
    /// 用户头像地址
    var avatarUrl: NSURL {
        return NSURL(string: userAccount?.avatar_large ?? "")!
    }
    
    /// 有效的 token
    var accessToken: String? {
        
        if !isExpired {
            return userAccount?.access_token
        }
        return nil
    }
    
    /// 是否过期
    var isExpired: Bool {
        if userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return false
        }
        return true
    }
    
    /// 登录标记
    var userLogon: Bool {
        return (userAccount?.access_token != nil) && !isExpired
    }
    
    /// 解档路径 - 计算型属性
    private var accountPath: String {
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    // MARK: 构造函数
    private init() {
        
        // 从沙盒中加载用户信息
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as?UserAccount
        
        // 如果是过期的 清空账号
        if isExpired {
            userAccount = nil
        }
    }
}

// MARK: - 用户相关的网络逻辑方法
extension UserAccountViewModel {
    
    ///  加载 token
    ///
    ///  - parameter code:     授权码
    ///  - parameter finished: 加载 token 是否成功
    func loadAccessToken(code: String, finished: (isSuccessed: Bool) -> ()) {
        
        // 加载 AccessToken
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil {
                finished(isSuccessed: false)
                return
            }
            
            self.userAccount = UserAccount(dict: result as! [String: AnyObject])
            
            // 加载用户信息
            self.loadUserInfo(self.userAccount!, finished: finished)
        }
    
    }
    
    ///  加载用户信息
    ///
    ///  - parameter account: 传入用户的 uid 获取用户的昵称和头像
    private func loadUserInfo(account: UserAccount, finished: (isSuccessed: Bool) -> ()) {
        
        NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            
            if error != nil {
                finished(isSuccessed: false)
            }
            
            guard let dict = result as? [String: AnyObject] else {
                print("数据格式不正确")
                finished(isSuccessed: false)
                return
            }
           // print(result)
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            // 将用户信息保存到沙盒
            //account.saveUserAccount()
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            print(self.accountPath)
            // 成功的回调
            finished(isSuccessed: true)
        }
    }

    
}